var fs = require('fs');
var path = require('path');

var code  = '';
var _size = 0;

// image
var FILE_TYPE = ['.jpg','.png','.gif'];
walk(path.join('./','image'),function (err,files){
  if(err){
    console.log(err);
    return;
  }
  files = files.filter(function (item){
    var extname = path.extname(item);
    if(FILE_TYPE.indexOf(extname)!=-1){
      return true;
    }
  });
  var results = [];
  for (var i = files.length - 1; i >= 0; i--) {
    var file = files[i];
    var extname = path.extname(file);
    var basename = path.basename(file,extname);
    var dirname = path.dirname(file);
    var file_info = fs.statSync(file);
    var item = {id:file,src:file,size:file_info.size};
    _size += item.size;
    results.push(item);
  }

  code += ' _IMAGES_RES =' +JSON.stringify(results) + ';';
  // var filePath = path.join('./','js', 'util', 'res.js');
  // fs.writeFileSync(filePath,code,'utf-8');
  loaded();
});

// tpl
walk(path.join('./','tpl'),function (err,files){
  if(err){
    console.log(err);
    return;
  }
  // files = files.filter(function (item){
  //   var extname = path.extname(item);
  //   return extname == 'html';
  //   // if(FILE_TYPE.indexOf(extname)!=-1){
  //   //   return true;
  //   // }
  // });
	// console.log(files);
  var results = [];
  for (var j=0, i=files.length - 1; i >= 0; i--) {
    var file = files[i];
    var extname = path.extname(file);
    var basename = path.basename(file,extname);
    var dirname = path.dirname(file);
    var file_info = fs.statSync(file);
    var item = {id:basename,src:file,size:file_info.size};
    // _size += item.size;
		
		(function(item, i) {fs.readFile(file, 'utf-8', function(err, data) {
			if(err) throw err;
				item.data = data;
				results.push(item);
				
				console.log(item.id, item.src, i);
			
				if(++j == files.length)
					success(results);
			});
			
		})(item, i);
	}
	
	var success = function(results) {
		// console.log(results);
		code += ' _TPL_RES =' +JSON.stringify(results) + ';';
		loaded();
	};
});

var count = 2;
function loaded() {
  if(--count <= 0) {
    code += ' _ALL_SIZE =' + _size + ';';
    var filePath = path.join('./','js', 'util', 'res.js');
    fs.writeFileSync(filePath,code,'utf-8');    
  }
}

function walk(dir, done) {
  var results = [];
  fs.readdir(dir, function(err, list) {
    if (err) return done(err);
    var pending = list.length;
    if (!pending) return done(null, results);
    list.forEach(function(file) {
      if (dir[dir.length - 1] == '/') {
        file = dir + file;
      } else {
        file = dir + '/' + file;
      }
      fs.stat(file, function(err, stat) {
        if (stat && stat.isDirectory()) {
          walk(file, function(err, res) {
            results = results.concat(res);
            if (!--pending) done(null, results);
          });
        } else {
          results.push(file);
          if (!--pending) done(null, results);
        }
      });
    });
  });
};